import { observer } from 'mobx-react'

import React, { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import {
    Form,
    Input,
    Button,
    DatePicker,
    Radio,
    Select,
    Checkbox,
    Card,
    message,
    Row,
    Col,
    Affix
} from 'antd'
import dayjs, { Dayjs } from 'dayjs'


interface Continent {
    label: string
    countries: string[]
}


const { RangePicker } = DatePicker
const { TextArea } = Input

// 模拟「模块权限」选项
const modules = [
    '首页', '用户', '数据', '体育', '娱乐', '交易', '营销', '代理', '风控', '设置',
]

const continentData: Continent[] = [
    {
        label: '亚洲',
        countries: ['中国', '日本', '印度', '沙特阿拉伯'],
    },
    {
        label: '欧洲',
        countries: ['德国', '法国', '英国', '意大利', '西班牙', '乌克兰'],
    },
    {
        label: '非洲',
        countries: ['南非', '埃及', '尼日利亚'],
    },
    {
        label: '北美洲',
        countries: ['美国', '加拿大', '墨西哥', '古巴', '巴哈马'],
    },
    {
        label: '南美洲',
        countries: ['巴西', '阿根廷', '哥伦比亚'],
    },
]
interface TreeNode {
    title: string // 节点显示名称
    key: string // 节点唯一标识
    children?: TreeNode[] // 子节点
}

// 租户权限-树形数据示例
const treeData: TreeNode[] = [
    {
        title: '首页',
        key: 'home',
    },
    {
        title: '用户',
        key: 'user',
        children: [
            {
                title: '用户查看',
                key: 'user.view',
            },
            {
                title: '用户创建',
                key: 'user.create',
            },
            {
                title: '用户编辑',
                key: 'user.edit',
            },
        ],
    },
    {
        title: '数据',
        key: 'data',
        children: [
            { title: '数据报表', key: 'data.report' },
            { title: '数据导出', key: 'data.export' },
        ],
    },
    // ...
]


// 表单的字段类型示例
interface TenantFormValues {
    name: string
    code: string
    validTime?: [Dayjs, Dayjs]
    domain?: string
    status: boolean
    description?: string
    // 租户权限
    modules?: string[]
    // 国家/地区
    countries?: string[]
}
const RoleManagementAdd: React.FC = () => {
    const [form] = Form.useForm()
    const navigate = useNavigate()
    const [loading, setLoading] = useState(false)

    // 模块选项多选
    const [checkedModules, setCheckedModules] = useState<string[]>(modules)
    // 存储已勾选的“国家”
    const [checkedCountries, setCheckedCountries] = useState<string[]>([])
    const allCountries = continentData.flatMap(c => c.countries)
    const isAllChecked = checkedCountries.length === allCountries.length
    // 是否部分选中
    const isIndeterminate =
        checkedCountries.length > 0 && !isAllChecked

    const onCheckAll = (e: any) => {
        if (e.target.checked) {
            // 全选
            setCheckedCountries(allCountries)
        } else {
            // 全部取消
            setCheckedCountries([])
        }
    }

    // 切换勾选某个国家
    const toggleCountry = (country: string, checked: boolean) => {
        let newList = [...checkedCountries]
        if (checked) {
            // 勾选
            newList.push(country)
            // 去重
            newList = Array.from(new Set(newList))
        } else {
            // 取消勾选
            newList = newList.filter(item => item !== country)
        }
        setCheckedCountries(newList)
    }


    // 提交表单
    const handleSubmit = async () => {
        try {
            const values = await form.validateFields()
            console.log('Success:', values, checkedCountries);
          setLoading(true)
          // TODO: 调用添加接口
          message.success('添加成功')
          navigate('/setting/enterpriseManagement/roleManagement')
        } catch (error) {
          message.error('添加失败')
        } finally {
          setLoading(false)
        }
    }
    return (
        <div className="add-app-detail">
            <div className="basic-info">
                <div className="title">基本信息</div>
                <Form<TenantFormValues>
                    form={form}
                    labelCol={{ span: 4 }}
                    initialValues={{
                        status: true, // 默认启用
                        modules: checkedModules,
                        countries: checkedCountries
                    }}
                >
                    {/* ======== 基本信息 ======== */}
                    <Form.Item
                        label="角色名称"
                        name="name"
                        rules={[{ required: true, message: '请输入角色名称' }]}
                    >
                        <Input placeholder="请输入角色名称" />
                    </Form.Item>
                    <Form.Item
                        label="角色标识"
                        name="roleId"
                        rules={[{ required: true, message: '请选择角色标识类型' }]}
                        initialValue="按钮" // 默认选哪项
                    >
                        <Radio.Group>
                            <Radio value="菜单">菜单</Radio>
                            <Radio value="按钮">按钮</Radio>
                            <Radio value="筛选">筛选</Radio>
                        </Radio.Group>
                    </Form.Item>

                    {/* 数据权限：下拉选择 */}
                    <Form.Item
                        label="数据权限"
                        name="dataPermission"
                        rules={[{ required: true, message: '请选择数据权限' }]}
                        initialValue="全部"
                    >
                        <Select placeholder="请选择数据权限">
                            <Select.Option value="全部">全部</Select.Option>
                            <Select.Option value="本级及子级">本级及子级</Select.Option>
                            <Select.Option value="本级">本级</Select.Option>
                            <Select.Option value="本人">本人</Select.Option>
                            <Select.Option value="自定义">自定义</Select.Option>
                        </Select>
                    </Form.Item>

                    <Form.Item label="角色描述" name="description">
                        <TextArea rows={4} placeholder="请输入角色描述，最多不超过200字。" maxLength={200} />
                    </Form.Item>
                    </Form>
            </div>
            <div className="basic-info">
                <div className="title">
                    <span style={{ marginRight: 10 }}>国家/地区</span>
                    <Checkbox
                        checked={isAllChecked}
                        indeterminate={isIndeterminate}
                        onChange={onCheckAll}
                    >
                        全选
                    </Checkbox>
                </div>
                    <div style={{ width: 600, marginLeft: '1em' }}>
                        {continentData.map(continent => (
                            <Row key={continent.label} style={{ marginBottom: 12 }}>
                                <Col style={{ marginRight: 16, width: 48, textAlign: 'right' }}>
                                    {continent.label}
                                </Col>
                                <Col>
                                    {continent.countries.map(country => (
                                        <Checkbox
                                            key={country}
                                            style={{ marginRight: 16 }}
                                            checked={checkedCountries.includes(country)}
                                            onChange={e => toggleCountry(country, e.target.checked)}
                                        >
                                            {country}
                                        </Checkbox>
                                    ))}
                                </Col>
                            </Row>
                        ))}
                    </div>
                </div>
                <div className="form-actions">
                    <Button type="primary" loading={loading} onClick={handleSubmit}>
                        保存
                    </Button>
                    <Button onClick={() => navigate(-1)}>返回</Button>
                </div>
        </div>
    )
}

export default observer(RoleManagementAdd)
